package com.test.google.app.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.test.google.app.domain.File;
import com.test.google.app.domain.SyncFileTask;
import com.test.google.app.service.FileService;
import com.test.google.app.service.SyncFileTaskService;
import com.test.google.app.util.DateUtil;
import com.test.google.app.util.JPAMng;
import com.test.google.app.util.MimeTypeUtil;

public class SyncFileTaskServiceImpl implements SyncFileTaskService {
	
	private DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
	private FileService fs = new FileServiceImpl();

	@Override
	public void delete(long id) {
		ds.delete(KeyFactory.createKey(SyncFileTask.KIND, id));
	}

	@Override
	public List<SyncFileTask> ListAll() {
		EntityManager mng = JPAMng.getEMF().createEntityManager();
		String sql = "select t from " + SyncFileTask.KIND + " t";
		List<SyncFileTask> list = mng.createQuery(sql, SyncFileTask.class).getResultList();
		mng.close();
		return list;
	}

	@Override
	public Entity getById(long id) throws EntityNotFoundException {
		return ds.get(KeyFactory.createKey(SyncFileTask.KIND, id));
	}

	@Override
	public void syncFile(SyncFileTask task) throws IOException {
		URL url = new URL(task.getTargetUrl());
		InputStream in = url.openStream();
		String path = ("/" + task.getLocalPath()).replaceAll("//", "/").trim();
		if (path.endsWith("/")) {
			path = path.substring(0, path.length()-1);
		}
		String name = path.substring(path.lastIndexOf("/") + 1);
		File file = new File();
		file.setCreateTime(DateUtil.dateTimeToString(new Date()));
		file.setMimeType(MimeTypeUtil.get(name));
		file.setName(name);
		file.setPath(path);
		byte[] bb = new byte[in.available()];
		in.read(bb);
		file.setContent(bb);
		file.setSize(bb.length);
		fs.saveOrUpdateByName(file);
		task.setLastSyncTime(DateUtil.dateTimeToString(new Date()));
		update(task);
		in.close();
	}
	
	@Override
	public void update(SyncFileTask task) {
		EntityManager mng = JPAMng.getEMF().createEntityManager();
		mng.merge(task);
		mng.close();
	}

	@Override
	public void add(SyncFileTask task) {
		EntityManager mng = JPAMng.getEMF().createEntityManager();
		mng.persist(task);
		mng.close();
	}

}
